<template>
  <div class="system-role-container">
    <el-card shadow="hover">
      <div class="system-user-search mb10">
        <pageSearch :searchformConfig="searchConfig" @handleQueryClick="handleQueryClick"
          @handleResetClick="handleResetClick" @handleAddClick="onOpenAddRole">
        </pageSearch>
      </div>

      <el-table-plus :pagination="pagination" :data="state.tableData.data" :columns="columns" :total="pagination.total"
        @page-change="handlePageChange" @prev-click="handlePageChange" @next-click="handlePageChange">
        <template #status="{ cellValue, row, column }">
          <el-tag class="ml-2" :type="row.status == 0 ? 'success' : 'danger'"
            :disable-transitions="true">{{row.status==0?'启用':'禁用'}}</el-tag>
        </template>

        <template #handle="{ cellValue, row, column }">
          <el-button :type="row.status == 0 ? 'danger' : 'success'" text size="small"
            v-if="state.tableData.auth.disabled"
            @click="handleDisEnd({ cellValue, row, column })">{{ row.status == 0 ? '禁用' : '启用' }}</el-button>
          <el-button type="primary" size="small" text @click="handleEdit({ cellValue, row, column })" v-if="state.tableData.auth.edit">编辑</el-button>
          <el-button type="danger" size="small" text @click="handleDel({ cellValue, row, column })" v-if="state.tableData.auth.delete">删除</el-button>
        </template>
        <template #handleTitle>操作</template>
      </el-table-plus>
    </el-card>

    <UsersForm ref="formRef" @on-load="handleQueryClick" />

  </div>
</template>
<script lang="ts" setup>
import { ref, toRefs, reactive, onMounted, watchEffect, defineComponent } from "vue"
import usePag from '/@/utils/table'
import { IForm } from '/@/types/form/search';
import pageSearch from '/@/components/search/page-search.vue';
import { success, confirm, error } from '/@/utils/msg'
import { usersApi } from '/@/api/system/users'

import UsersForm from '/@/views/system/account/form.vue'
import {checkAuth} from '/@/utils/authFunction'


interface TableDataState {
  tableData: {
    data: Array<any>,
    params: {
      id?: string
      keys: string
    },
    auth?:any
  }
}

const formRef = ref()

// 分页设置
const { PagStore } = usePag()

// 表头数据
const columns: any = [
  //{ label: "序号", type: "index", prop: "index", width: "60" },
  { label: "账户名称", prop: "username", width: '120', "show-overflow-tooltip": true },
  { label: "用户昵称", prop: "nickname", width: '160' },
  { label: "关联角色", prop: "roles", "show-overflow-tooltip": true },
  { label: "手机号", prop: "phone" },
  { label: "邮箱", prop: "email", "show-overflow-tooltip": true },
  {
    label: "用户状态", prop: "status", slots: {
      customRender: "status"
    }
  },
  {
    label: "操作",
    fixed: "right",
    prop: "handle",
    width: "130",
    align: "right",
    slots: {
      customRender: "handle",
      customTitle: "handleTitle",
    },
  }
];

// 表格数据
const state = reactive<TableDataState>({
  tableData: {
    data: [],
    params: {
      id: '',
      keys: ''
    },
    auth: {
      create:checkAuth('admin/users/add'),
      edit:checkAuth('admin/users/detail'),
      delete:checkAuth('admin/users/delete'),
      disabled:checkAuth('admin/users/disenabled'),

    }
  }
});

// 分页
const pagination = reactive({ ...state.tableData.params, ...PagStore });

// 加载列表
const dataList = async () => {
  const { currentPage, pageSize } = { ...pagination }
  const param = { ...state.tableData.params, pageSize, currentPage }
  return await usersApi().dataList(param)
}

// 删除
const deleteRole = async (param) => {
  return await usersApi().delete(param)
}

// 初始化数据列表
const initTableData = async () => {
  const ds = await dataList()
  const { data, total } = { ...ds }
  pagination.total = total
  state.tableData.data = data
}

// 页面加载时
onMounted(() => {
  initTableData()
})

const colAttrs = {
  align: "left",
  border:'border'
};

// 删除角色
const handleDel = async (a: any) => {
  confirm(`此操作将永久删除用户帐户：“${a.row.username}”，是否继续?`).then(async () => {
    const { code, msg } = await deleteRole(a.row)
    if (code == 0 || code == true) {
      success(msg)
      initTableData()
    }
  }).catch(() => { })
}

// 编辑
const handleEdit = (a: any) => {
  formRef.value.openDialog(a.row, '编辑')
}

// 选择页面重新加载
const handlePageChange = (a: any) => {
  pagination.currentPage = a.currentPage
  initTableData()
}

// 打开新增角色弹窗
const onOpenAddRole = (a: any) => {
  formRef.value.openDialog({})
}

// 查询
const handleQueryClick = (value: any) => {
  state.tableData.params = { ...value }
  initTableData()
}

// 重置
const handleResetClick = () => {
  console.log('重置');
};

// 启用/禁用
const handleDisEnd = (a: any) => {
  confirm(`确认${a.row.status==0?'禁用':'启用'} ”${a.row.username}” 该操作?`).then(async()=>{
    const {code,msg} = await usersApi().disenabled({id:a.row.id})
    if ( code == 0 || code == true ) {
      success(msg)
      initTableData()
    } else {
      error(msg)
    }
  })
}

// 搜索配置
const searchConfig: IForm = {
  formItems: [
    { field: 'keys', type: 'input', label: '用户名', placeholder: '请输入 关键字' },
  ]
}

defineExpose({
  formRef
})
</script>